<template>
  <section>
    <!--工具条-->
    <el-row>
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" size="small" :model="filters" @submit.native.prevent>
          <el-form-item>
            <el-input v-model="filters.label" placeholder="菜单名或路径" @keyup.enter.native="onGetList">
              <i slot="prefix" class="el-input__icon el-icon-search" />
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onGetList">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onAdd">新增</el-button>
          </el-form-item>
          <el-form-item>
            <confirm-button
              :icon="'el-icon-refresh'"
              :placement="'bottom-end'"
              :loading="syncLoading"
              style="margin:0px;"
              @click="onSync"
            >
              <p slot="content">确定要同步菜单吗？</p>同步菜单
            </confirm-button>
          </el-form-item>
          <el-form-item>
            <confirm-button
              v-if="sels.length > 0"
              :type="'delete'"
              :placement="'bottom-end'"
              :loading="deleteLoading"
              style="margin-left: 0px;"
              @click="onBatchDelete"
            >
              <p slot="content">确定要批量删除吗？</p>批量删除
            </confirm-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!--列表-->
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      row-key="id"
      :data="viewTree"
      :default-expand-all="false"
      :expand-row-keys="expandRowKeys"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      highlight-current-row
      style="width: 100%;"
      stripe="true"
      fit="true"
      @select-all="onSelectAll"
      @select="onSelect"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" width="50" />
      <el-table-column prop="key" label="菜单路径" width="350" />
      <el-table-column prop="title" label="菜单标题" width="160" />
      <el-table-column prop="icon" label="菜单图标" width />
      <el-table-column prop="component" label="组件名称" width="180" />
      <el-table-column prop="isEnable" label="状态" width="80" align="center" header-align="center">
        <template v-slot="scope">
          <el-tag
            :type="scope.row.isEnable ? 'success' : 'danger'"
            disable-transitions
          >{{ scope.row.isEnable ? '正常' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="50" align="center" />
      <el-table-column label="操作" width="180" align="center" header-align="center">
        <template v-slot="{ $index, row }">
          <el-button size="small" @click="onEdit($index, row)">编辑</el-button>
          <confirm-button type="delete" :loading="row._loading" @click="onDelete($index, row)" />
        </template>
      </el-table-column>
    </el-table>

    <!--编辑界面-->
    <el-drawer
      v-model="editFormVisible"
      title="编辑"
      :visible.sync="editFormVisible"
      :wrapper-closable="true"
      class="el-drawer__wrapper"
      size="'auto'"
      direction="btt"
      @close="onCloseEditForm"
    >
      <section style="padding:24px 48px 74px 24px;">
        <el-form ref="editForm" :model="editForm" :inline="false" size="small" :rules="editFormRules" label-width="80px">

          <el-row>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="菜单key" prop="key">
                <el-input v-model="editForm.key" auto-complete="off" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="菜单标题" prop="title">
                <el-input v-model="editForm.title" auto-complete="off" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="菜单图标" prop="icon">
                <el-input v-model="editForm.icon" auto-complete="off" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="组件名称" prop="component">
                <el-input v-model="editForm.component" auto-complete="off" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="完全匹配" prop="exact">
                <el-select v-model="editForm.exact" placeholder="请选择是否完全匹配" style="width:100%;">
                  <el-option
                    v-for="item in yesOrNoList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="是否启用" prop="isEnable">
                <el-select v-model="editForm.isEnable" placeholder="请选择状态" style="width:100%;">
                  <el-option
                    v-for="item in statusList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="是否隐藏" prop="isHidden">
                <el-select v-model="editForm.isHidden" placeholder="请选择是否完全匹配" style="width:100%;">
                  <el-option
                    v-for="item in yesOrNoList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="是否关闭" prop="closable">
                <el-select v-model="editForm.closable" placeholder="请选择角色状态" style="width:100%;">
                  <el-option
                    v-for="item in yesOrNoList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="是否展开" prop="opened">
                <el-select v-model="editForm.opened" placeholder="请选择角色状态" style="width:100%;">
                  <el-option
                    v-for="item in yesOrNoList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="editForm.sort" auto-complete="off" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item prop="parentIds" label="父级菜单">
                <el-cascader
                  :key="editFormKey"
                  v-model="editForm.parentIds"
                  placeholder="请选择，支持搜索功能"
                  :options="modules"
                  :props="{ checkStrictly: true, value: 'id' }"
                  filterable
                  style="width:100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="说明" prop="description">
                <el-input v-model="editForm.description" auto-complete="off" />
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </section>
      <div class="drawer-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <confirm-button :validate="editFormValidate" :loading="editLoading" @click="onEditSubmit" />
      </div>
    </el-drawer>

    <!--新增界面-->
    <el-drawer
      v-model="addFormVisible"
      title="新增"
      :visible.sync="addFormVisible"
      :wrapper-closable="true"
      class="el-drawer__wrapper"
      size="'auto'"
      direction="btt"
      @close="onCloseAddForm"
    >
      <section style="padding:24px 48px 74px 24px;">
        <el-form ref="addForm" :model="addForm" label-width="80px" :rules="addFormRules" :inline="false" size="small">
          <el-row>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="菜单key" prop="key">
                <el-input v-model="addForm.key" auto-complete="off" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="菜单标题" prop="title">
                <el-input v-model="addForm.title" auto-complete="off" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="菜单图标" prop="icon">
                <el-input v-model="addForm.icon" auto-complete="off" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="组件名称" prop="component">
                <el-input v-model="addForm.component" auto-complete="off" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="完全匹配" prop="exact">
                <el-select v-model="addForm.exact" placeholder="请选择是否完全匹配" style="width:100%;">
                  <el-option
                    v-for="item in yesOrNoList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="是否启用" prop="isEnable">
                <el-select v-model="addForm.isEnable" placeholder="请选择状态" style="width:100%;">
                  <el-option
                    v-for="item in statusList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="是否隐藏" prop="isHidden">
                <el-select v-model="addForm.isHidden" placeholder="请选择是否完全匹配" style="width:100%;">
                  <el-option
                    v-for="item in yesOrNoList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="是否关闭" prop="closable">
                <el-select v-model="addForm.closable" placeholder="请选择角色状态" style="width:100%;">
                  <el-option
                    v-for="item in yesOrNoList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="是否展开" prop="opened">
                <el-select v-model="addForm.opened" placeholder="请选择角色状态" style="width:100%;">
                  <el-option
                    v-for="item in yesOrNoList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="addForm.sort" auto-complete="off" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item prop="parentIds" label="父级菜单">
                <el-cascader
                  :key="addFormKey"
                  v-model="addForm.parentIds"
                  placeholder="请选择，支持搜索功能"
                  :options="modules"
                  :props="{ checkStrictly: true, value: 'id' }"
                  filterable
                  style="width:100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="说明" prop="description">
                <el-input v-model="addForm.description" auto-complete="off" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </section>
      <div class="drawer-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <confirm-button :validate="addFormValidate" :loading="addLoading" @click="onAddSubmit" />
      </div>
    </el-drawer>
  </section>
</template>

<script>
import { formatTime, treeToList, listToTree, getTreeParents } from '@/utils'
import {
  getMenuList,
  removeMenu,
  editMenu,
  addMenu,
  batchRemoveMenu,
  getMenu
} from '@/api/react/menu'
import ConfirmButton from '@/components/ConfirmButton'

export default {
  name: 'Menu',
  components: {
    ConfirmButton
  },
  data() {
    return {
      filters: {
        label: ''
      },
      viewTree: [],
      expandRowKeys: [],
      listLoading: false,
      sels: [], // 列表选中列
      statusList: [
        { name: '激活', value: true },
        { name: '禁用', value: false }
      ],
      yesOrNoList: [
        { name: '是', value: true },
        { name: '否', value: false }
      ],
      addDialogFormVisible: false,
      editFormVisible: false, // 编辑界面是否显示
      editLoading: false,
      editFormRules: {
        parentIds: [{ required: true, message: '请选择父级菜单', trigger: 'change' }],
        key: [{ required: true, message: '请输入菜单key', trigger: 'blur' }],
        title: [{ required: true, message: '请输入菜单标题', trigger: 'blur' }],
        exact: [{ required: true, message: '请选择菜单是否完全匹配', trigger: 'change' }],
        isEnable: [{ required: true, message: '请选择菜单是否启用', trigger: 'change' }],
        isHidden: [{ required: true, message: '请选择菜单是否隐藏', trigger: 'change' }],
        closable: [{ required: true, message: '请选择菜单是否关闭', trigger: 'change' }],
        opened: [{ required: true, message: '请选择菜单是否展开', trigger: 'change' }],
        sort: [{ required: true, message: '请输入菜单排序', trigger: 'blur' }]

      },
      // 编辑界面数据
      editForm: {
        id: 0,
        parentIds: [],
        key: '',
        title: '',
        icon: '',
        component: '',
        exact: true,
        isEnable: true,
        isHidden: false,
        closable: false,
        opened: false,
        sort: 0,
        Description: ''
      },
      editFormKey: 1,

      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      addFormRules: {
        parentIds: [{ required: true, message: '请选择所属模块', trigger: 'change' }],
        key: [{ required: true, message: '请输入菜单key', trigger: 'blur' }],
        title: [{ required: true, message: '请输入菜单标题', trigger: 'blur' }],
        exact: [{ required: true, message: '请选择菜单是否完全匹配', trigger: 'change' }],
        isEnable: [{ required: true, message: '请选择菜单是否启用', trigger: 'change' }],
        isHidden: [{ required: true, message: '请选择菜单是否隐藏', trigger: 'change' }],
        closable: [{ required: true, message: '请选择菜单是否关闭', trigger: 'change' }],
        opened: [{ required: true, message: '请选择菜单是否展开', trigger: 'change' }],
        sort: [{ required: true, message: '请输入菜单排序', trigger: 'blur' }]
      },
      // 新增界面数据
      addForm: {
        parentIds: [],
        key: '',
        title: '',
        icon: '',
        component: '',
        exact: true,
        isEnable: true,
        isHidden: false,
        closable: false,
        opened: false,
        sort: 0,
        Description: ''
      },
      addFormKey: 1,
      modules: [],
      syncLoading: false,
      deleteLoading: false
    }
  },
  mounted() {
    this.onGetList()
  },
  methods: {
    formatCreatedTime: function(row, column, time) {
      return formatTime(time, 'yyyy-MM-dd hh:mm')
    },
    // 获取列表
    async onGetList() {
      const para = {
        key: this.filters.label
      }
      this.listLoading = true
      const res = await getMenuList(para)
      this.listLoading = false

      if (!res.success) {
        if (res.msg) {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
        return
      }

      const list = _.cloneDeep(res.data)
      debugger
      const keys = list.filter(l => l.parentId === 0).map(l => l.id + '')
      // 为数组的每一项提供一个label用于展示
      const listToSelect = list.map(s => {
        return Object.assign({}, s, { label: s.title, level: s.sort })
      })
      this.expandRowKeys = keys

      this.modules = listToTree(_.cloneDeep(listToSelect), {
        id: 0,
        parentId: 0,
        label: '根节点'
      })

      list.forEach(l => {
        l._loading = false
      })

      const tree = listToTree(list)
      this.sels = []
      this.viewTree = tree
    },
    // 显示编辑界面
    async onEdit(index, row) {
      const loading = this.$loading()
      const res = await getMenu({ id: row.id })
      loading.close()
      if (res && res.success) {
        const parents = getTreeParents(this.viewTree, row.id)
        const parentIds = parents.map(p => p.id)
        parentIds.unshift(0)

        const data = res.data
        data.parentIds = parentIds
        this.editForm = data
        this.editFormVisible = true
        ++this.editFormKey
      }
    },
    onCloseEditForm() {
      this.$refs.editForm.resetFields()
      ++this.editFormKey
    },
    // 显示新增界面
    onAdd() {
      this.addFormVisible = true
    },
    onCloseAddForm() {
      this.$refs.addForm.resetFields()
      ++this.addFormKey
    },
    // 编辑
    editFormValidate: function() {
      let isValid = false
      this.$refs.editForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    async onEditSubmit() {
      debugger
      this.editLoading = true
      const para = _.cloneDeep(this.editForm)
      para.parentId = para.parentIds.pop()
      if (para.id === para.parentId) {
        this.$message({
          message: '所属模块不能是自己！',
          type: 'error'
        })
        this.editLoading = false
        return
      }

      const res = await editMenu(para)
      this.editLoading = false
      if (res.success) {
        this.$message({
          message: this.$t('admin.updateOk'),
          type: 'success'
        })
        this.$refs['editForm'].resetFields()
        this.editFormVisible = false
        this.onGetList()
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 新增
    addFormValidate: function() {
      let isValid = false
      this.$refs.addForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    async onAddSubmit() {
      this.addLoading = true
      const para = _.cloneDeep(this.addForm)
      para.parentId = para.parentIds.pop()

      const res = await addMenu(para)
      this.addLoading = false

      if (res.success) {
        this.$message({
          message: this.$t('admin.addOk'),
          type: 'success'
        })
        this.$refs['addForm'].resetFields()
        this.addFormVisible = false
        this.onGetList()
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        })
      }
    },
    // 删除
    async onDelete(index, row) {
      row._loading = true
      const para = { id: row.id }
      const res = await removeMenu(para)

      row._loading = false

      if (!res.success) {
        this.$message({
          message: res.msg,
          type: 'error'
        })
        return
      }
      this.$message({
        message: this.$t('admin.deleteOk'),
        type: 'success'
      })
      this.onGetList()
    },
    // 批量删除
    async onBatchDelete() {
      const para = { ids: [] }
      para.ids = this.sels.map(s => {
        return s.id
      })

      this.deleteLoading = true
      const res = await batchRemoveMenu(para.ids)
      this.deleteLoading = false

      if (res.success) {
        this.$message({
          message: this.$t('admin.batchDeleteOk'),
          type: 'success'
        })
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        })
      }

      this.onGetList()
    },
    // 同步view
    async onSync() {
      const unFinish = true
      if (unFinish) {
        this.$message({
          message: '开发中',
          type: 'info'
        })
        return
      }

      // this.syncLoading = true

      // const views = []

      // const r = await syncView({ views })

      // if (r) {
      //   if (r.success) {
      //     this.$message({
      //       message: this.$t('view.sync'),
      //       type: 'success'
      //     })
      //     this.onGetList()
      //   } else {
      //     this.$message({
      //       message: r.msg,
      //       type: 'error'
      //     })
      //   }
      // }
      // this.syncLoading = false
    },
    // 生成前端view
    onGenerate() {
      // let bb = this.sels
    },
    onSelectAll: function(selection) {
      const selections = treeToList(selection)
      const rows = treeToList(this.viewTree)
      const checked = selections.length === rows.length
      rows.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row, checked)
      })

      this.sels = this.$refs.multipleTable.selection
    },
    onSelect: function(selection, row) {
      const checked = selection.some(s => s.id === row.id)
      if (row.children && row.children.length > 0) {
        const rows = treeToList(row.children)
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, checked)
        })
      }

      this.sels = this.$refs.multipleTable.selection
    }
  }
}
</script>
